//
//  DiscoveryViewController.m
//  XPhoto
//
//  Created by baboy on 2019/2/20.
//  Copyright © 2019 baboy. All rights reserved.
//

#import "ExploreViewController.h"
#import "Post.h"
#import "BKAnnotation.h"
#import "BKAnnotationView.h"
#import "BKCollectionViewLayout.h"
#import "BKCollectionViewCell.h"
#import "Theme.h"
#import "ExploreCollectionCell.h"
#import "PostDetailViewController.h"
#import "ExploreSearchResultsViewController.h"
#import "SysDict.h"
#import "UIScrollView+x.h"
#import "Explore.h"

#define POST_CELL_REUSE_ID @"post_collection_cell"

@interface ExploreViewController ()<BKCollectionViewLayoutDelegate, UICollectionViewDelegate, UICollectionViewDataSource, ExploreCollectionCellDelegate,BKScrollViewDragRefreshDelegate,BKTabBarViewDelegate>
@property(nonatomic, strong) NSMutableArray *items;
@property(nonatomic, strong) BKCollectionViewLayout *collectionViewLayout;
@property(nonatomic, strong) UISearchController *searchController;
@property(nonatomic, strong) ExploreSearchResultsViewController *searchResultsController;
@end

@implementation ExploreViewController
- (id)init{
    if (self = [super initWithNibName:NSStringFromClass([self class]) bundle:nil]){
    }
    return self;
}
- (UISearchController *)searchController{
    if (!_searchController) {
        _searchResultsController = [[ExploreSearchResultsViewController alloc] init];
        _searchController = [[UISearchController alloc] initWithSearchResultsController:_searchResultsController];
        _searchController.searchResultsUpdater = self;
        [_searchController setActive:NO];
        _searchController.hidesNavigationBarDuringPresentation = NO;
        _searchController.obscuresBackgroundDuringPresentation = NO;
        _searchController.dimsBackgroundDuringPresentation = NO;
        _searchController.searchBar.searchBarStyle = UISearchBarStyleMinimal;
        _searchController.searchBar.placeholder = NSLocalizedString(@"search", @"按钮");
        _searchController.searchBar.backgroundColor = self.view.backgroundColor;
//        _searchController.searchBar.tintColor = [UIColor clearColor];
//        _searchController.searchBar.barTintColor = [UIColor whiteColor];
        _searchController.searchBar.delegate = self;
//        _searchController.searchBar.layer.borderColor = [UIColor redColor].CGColor;
//        _searchController.searchBar.layer.borderWidth = 1;
        _searchController.searchBar.returnKeyType = UIReturnKeySearch;
        self.definesPresentationContext = YES;
    }
    return _searchController;
}
- (BKCollectionViewLayout *)collectionViewLayout{
    if (!_collectionViewLayout) {
        _collectionViewLayout = [[BKCollectionViewLayout alloc] init];
        _collectionViewLayout.layoutMode = BKCollectionViewLayoutModeColumnAndRowSpan;
        _collectionViewLayout.numberOfColumns = 3;
        _collectionViewLayout.delegate = self;
    }
    return _collectionViewLayout;
}
- (void)initConfig{
    SysDict *exploreCategoryDict = [SysDict dictForKey:SYS_DICT_EXPLORE_CATEGORY_KEY];
    CGFloat topViewHeight = self.searchView.searchBar.superview.bounds.size.height;
    if (exploreCategoryDict) {
        self.categoryView.items = exploreCategoryDict.items;
        topViewHeight += self.categoryView.bounds.size.height;
    }
    self.categoryView.hidden = exploreCategoryDict ? NO : YES;
    NSLayoutConstraint *topViewHeightConstraint = [self.categoryView.superview constraintForAttribute:NSLayoutAttributeHeight firstItem:self.categoryView.superview secondItem:nil];
    topViewHeightConstraint.constant = topViewHeight;
    
    SysDict *exploreSearchTypeDict = [SysDict dictForKey:SYS_DICT_EXPLORE_SEARCH_TYPE_KEY];
    if (exploreSearchTypeDict) {
        self.searchView.categoryView.items = exploreSearchTypeDict.items;
    }
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    [self initConfig];
    self.searchView.tableView.tableFooterView = [UIView new];
    self.collectionView.backgroundColor = THEME_VIEW_BG_COLOR;
    self.collectionView.collectionViewLayout = self.collectionViewLayout;
//    self.topBarHeightConstraint.constant = self.searchController.searchBar.bounds.size.height + self.categoryScrollView.bounds.size.height;
//    [self.searchBarContainerView addSubview:self.searchController.searchBar];
    
//    UINib *headerViewNib = [UINib nibWithNibName:NSStringFromClass([PhotoListHeaderView class]) bundle:nil];
//    [self.collectionView registerNib:headerViewNib forSupplementaryViewOfKind: SUPPLEMENTARY_KIND_HEADER_VIEW withReuseIdentifier: PHOTO_HEADER_VIEW_REUSE_ID];
    UINib *postNib = [UINib nibWithNibName:NSStringFromClass([ExploreCollectionCell class]) bundle:nil];
    [self.collectionView registerNib:postNib forCellWithReuseIdentifier:POST_CELL_REUSE_ID];
    
    
    [self searchWithOffset:0];
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.navigationController.navigationBar.hidden = YES;
}
- (void)searchWithOffset:(NSInteger)offset{
    ExploreSearchArgs *args = [ExploreSearchArgs new];
    args.offset = offset;
    args.pageSize = 30;
    [Explore searchPostsWithArgs:args callback:^(id  _Nonnull task, NSArray *posts, NSError * _Nonnull error) {
        if (error) {
            [BKIndicator showMessageAndFadeOut:error.localizedDescription completion:nil];
        }
        if (!error) {
            if (offset == 0) {
                self.items = [NSMutableArray array];
            }
            [self.items addObjectsFromArray:posts];
        }
        [self.collectionView reloadData];
        [self.collectionView stopLoading];
        self.collectionView.loadMore = posts.count == args.pageSize;
        
    }];
}
#pragma mark - BKScrollViewDragRefreshDelegate
- (void)scrollViewWillBeginLoadingMore:(id)scrollView{
    [self searchWithOffset:self.items.count];
}

#pragma mark - UIScrollViewDelegate
-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
    [self.collectionView scrollViewDidScroll];
}
-(void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
    [self.collectionView scrollViewDidEndDragging];
}

#pragma mark - UICollectionViewDelegate
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return self.items.count;
}
/**
 * 元素高度
 */
- (CGFloat) collectionViewLayout:(id)layout heightForItemInSection:(NSInteger)section{
    CGFloat h = 128;
    return h;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    ExploreCollectionCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier: POST_CELL_REUSE_ID forIndexPath:indexPath];
    cell.delegate = self;
    Post *post = [self.items objectAtIndex:indexPath.item];
    cell.backgroundColor = [UIColor grayColor];
//    cell.layer.borderColor = [UIColor whiteColor].CGColor;
//    cell.layer.borderWidth = 1.0f;
    cell.post = post;
    return cell;
}
#pragma  ExploreCollectionCell Delegate
- (void)exploreCollectionCellDidClickedImage:(ExploreCollectionCell *)cell{
    Post *post = cell.post;
    PostDetailViewController *vc = [[PostDetailViewController alloc] init];
    vc.post = post;
    [self.navigationController pushViewController:vc animated:YES];
}
#pragma UISearchBar delegate
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText{
    DLOG(@"search:%@", searchText);
//    self.searchResultsController.keyword = searchText;
}
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar{
    [self.searchController.searchBar resignFirstResponder];
}

- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar {
    [self.searchController.searchBar resignFirstResponder];
}
- (void)updateSearchResultsForSearchController:(UISearchController *)searchController {
//    self.edgesForExtendedLayout = UIRectEdgeNone;
    searchController.searchResultsController.view.hidden = NO;
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
